import { addCouponData, stopCouponData } from "@Api/discountsApi/couponApi"
import {
  checkPromotionProductList,
  getProdectList,
  getPromotionProductList,
  getSkuList
} from "@Api/productApi"
import { message } from "@bytedance/mona-ui"
import moment from "moment"

import { generateRandomString } from "../../../jinritemaiCopyGoods/copyDataFomate"

let stopKet = false

export const addCouponFun = (data, cb) => {
  // console.log('addCun', data)
  return new Promise((resolve, reject) => {
    const { addCouponConfig, upDataInfo, selectGoodsKeys } = data
    const {
      period_type,
      goodsScope,
      start_time,
      expire_time,
      start_apply_time,
      valid_period,
      end_apply_time,
      couponGoodsNum,
      couponAfterText
    } = JSON.parse(JSON.stringify(addCouponConfig))
    if (goodsScope === 1) {
      // console.log('选择的是指定商品', selectGoodsKeys)
      if (!selectGoodsKeys || !selectGoodsKeys.length) {
        return message.warning("请选择商品后开始！！！")
      }
    }
    // console.log('是全店，或者有商品')
    const updata = {
      ignore: false,
      displayChannel: 1, // 1全网公开
      // "coupon_name": new Date().getTime() + '',
      period_type, // 1 限制日期范围 2 限制日期天数
      // discountType, // 1立减 2满减 3折扣---
      // "total_amount": 134, // 发行量 **** ---
      // "max_apply_times": 1, // 每人限领 **** ---
      goodsScope, // 1指定商品 2 全店商品
      // "goods": [], // goodsScope === 1  时的选择商品列表 ****
      // "threshold": 122000, // 满多少金额 ****
      // "credit": 100, // 立减金额 ****

      ...(() => {
        if (period_type === 1) {
          return {
            start_time, // 使用开始时间
            expire_time // 使用结束时间
          }
        }
        return {
          valid_period // 领取后几天使用
        }
      })(),
      start_apply_time, // 领取开始时间
      end_apply_time, // 领取结束时间
      support_type: goodsScope === 1 ? 1 : 5, // 1指定 5全店
      jump_type: goodsScope === 1 ? 4 : 3, // 4指定商品 3全店商品
      channel: 0,
      from_page: ""
      // "discount": 88 // 8.8折 ****
    }
    const quanDataListAllGood = []
    const upInfoData = JSON.parse(JSON.stringify(upDataInfo))

    for (let i = 0; i < upInfoData.length; i++) {
      quanDataListAllGood.push(setUpDataInfo(upInfoData[i]))
    }

    const quanDataListGoods = []
    if (goodsScope === 1) {
      const goodsShopList = []

      const selectData = JSON.parse(JSON.stringify(selectGoodsKeys))
      while (selectData && selectData.length) {
        goodsShopList.push(selectData.splice(0, couponGoodsNum))
      }
      quanDataListAllGood.forEach((item) => {
        goodsShopList.forEach((pit) => {
          const getitem = JSON.parse(JSON.stringify(item))
          getitem.goods = pit

          quanDataListGoods.push(getitem)
        })
      })
    }
    const upDataInfoEnd =
      goodsScope === 1 ? quanDataListGoods : quanDataListAllGood

    upDataInfoEnd.forEach((item, index) => {
      item.coupon_name = ""
      if (item.goodsScope === 1) {
        const idTypei =
          item.goods.length === 1 ? item.goods[0] : `${item.goods.length}个-`
        item.coupon_name = `${couponAfterText}商品-${idTypei}-${generateRandomString(
          3
        )}`
      } else {
        item.coupon_name = `${couponAfterText}全店-${moment().format(
          "YYYYMMDDHHmmss"
        )}-${generateRandomString(3)}`
      }
      item.coupon_name = item.coupon_name.slice(0, 25)
    })

    const allInstallNum = JSON.parse(JSON.stringify(upDataInfoEnd)).length
    let addUnser = 0
    let success = 0
    let fail = 0
    upCouponListFun(upDataInfoEnd)

    function upCouponListFun(dataList) {
      const data = dataList.splice(0, 1)
      if (data && data.length) {
        // console.log('优惠券列表：', data[0])
        // const setData = setUpDataInfo(data[0])
        // console.log('创建前的数据：：：', setData)
        cb &&
          cb({
            resetData: data[0],
            addUnser,
            allInstallNum,
            stip: ((addUnser / allInstallNum) * 100).toFixed(2),
            stopKet,
            success,
            fail
          })
        if (stopKet) {
          message.warning("已手动停止创建优惠券")
          return
        }
        addOneCouponFun(data[0])
          .then((res) => {
            addUnser++
            success++
            cb &&
              cb({
                resetData: data[0],
                addUnser,
                allInstallNum,
                stip: ((addUnser / allInstallNum) * 100).toFixed(2),
                stopKet,
                success,
                fail
              })
            setTimeout((_) => {
              upCouponListFun(dataList)
            }, 2000)
          })
          .catch((err) => {
            fail++
            addUnser++
            cb &&
              cb({
                resetData: data[0],
                addUnser,
                allInstallNum,
                stip: ((addUnser / allInstallNum) * 100).toFixed(2),
                stopKet,
                success,
                fail
              })
            err.msg && message.error(err.msg)
            setTimeout((_) => {
              upCouponListFun(dataList)
            }, 2000)
          })
      } else {
        console.log("创建完成")
        resolve("创建完成")
      }
    }
    function setUpDataInfo(data) {
      const {
        total_amount,
        max_apply_times,
        discountType,
        threshold,
        credit,
        discount
      } = data
      // console.log('credit', credit, discountType)
      // console.log('threshold', threshold)
      // console.log('discount', discount)
      const upDataSetInfoOns = {
        total_amount,
        max_apply_times,
        goods: null,
        discountType,
        threshold: discountType === 2 ? threshold * 100 : null,
        credit: discountType === 2 || discountType === 1 ? credit * 100 : null,
        discount: discountType === 3 ? discount * 10 : null,
        favoured_type: (() => {
          // 22 全店立减 42 指定立减 23全店满减 43指定满减 41指定折扣 21全店折扣 ****
          let oneNum = goodsScope === 1 ? "4" : "2"
          let towNum = discountType === 1 ? "2" : discountType === 2 ? "3" : "1"
          return `${oneNum}${towNum}` * 1
        })()
      }

      Object.keys(upDataSetInfoOns).forEach((key) => {
        if (!upDataSetInfoOns[key]) {
          delete upDataSetInfoOns[key]
        }
      })
      return { ...updata, ...upDataSetInfoOns }
    }
  })
}
const addOneCouponFun = (data) => {
  return new Promise((resolve, reject) => {
    addCouponData(data)
      .then((res) => {
        console.log("设置优惠券结果", res)
        if (res.code && res.msg) {
          // 重新处理请求
          reject(res)
          // return message.error(res.msg)
        }
        resolve(res)
      })
      .catch((err) => {
        console.log("err这里重新发起请求", err)
        reject(err)
      })
  })
}

export const getProdectListFun = async (data) => {
  const res = await getProdectList(data)
  return res
}

export const stopAddConter = () => {
  stopKet = true
  setTimeout((_) => {
    stopKet = false
  }, 5000)
}
export const stopCouponFun = (data, cb) => {
  // if(!data || !data.length) {
  //     return
  // }
  const StopAddCouponList = data.map((item) =>
    stopCouponData(item, { action: 1 })
  )
  Promise.all(StopAddCouponList).then((res) => {
    console.log("res", res)
    cb && cb(res)
  })
  // stopCouponData(data[0], {"action":1}).then(res => {
  //     console.log('res', res)
  //     cb && cb(res)
  // })
}

let noContentList
export function getProductListWork(configList) {
  // 1.创建worker
  // 2.worker内的工作
  // 2.1获取所有的商品 marketing/activity/v1/query_available_product_v2
  // 2.2过滤无效的商品 即in_campaign === 1 为无效的商品
  // 2.3过滤相同的活动配置，即活动时间完全相同的活动表示为同一活动（只需获取一份商品列表）
  // 2.4 使用过滤后的商品与过滤后的活动列表调用 marketing/promotion/v1/check_promotion_validation 接口检查符合指定活动的商品
  // 3.worker内的工作完成后的回调
  // 4. 使用 marketing/promotion/v1/batch_query_sku_list_v2 获取sky列表
  // {
  //     "page": 4,
  //         "pageSize": 10,
  //             "activityToolType": 7,
  //                 "start_time": 1719244800,
  //                     "end_time": 1721923199,
  //                         "activitySubType": {
  //         "coupon_sub_type": 1
  //     }
  // }
  return new Promise((resolve, reject) => {
    const getActPrdList = {
      page: 1,
      pageSize: 100,
      activityToolType: 7,
      // "product_id": "3684570914181218576",
      business_code: "",
      start_time: "",
      end_time: "",
      activitySubType: {
        coupon_sub_type: 1
      }
      // "limit_stock_type": 0,
      // "config_scope": 0
    }

    getPromotionProductList(getActPrdList)
      .then((res) => {
        if (!res.code) {
          const getallData = []
          while (getActPrdList.pageSize * getActPrdList.page < res.total) {
            getActPrdList.page++
            getallData.push(getPromotionProductList(getActPrdList))
          }
          Promise.all(getallData).then((resit) => {
            let datas = res.data

            resit.forEach((resdata) => {
              datas.push(...resdata.data)
            })
            noContentList = datas.filter((item) => item.in_campaign === 0)
            datas = []
            console.log("noContentList", noContentList)
            // return
            checkPromotionValidationFun(configList).then((res) => {
              resolve(res)
            })
          })
        } else {
          console.log("未登陆，没权限等情况，在拦截器内部处理")
        }
      })
      .catch((err) => {
        console.log("返回的消息", err)
        reject(err)
      })
  })
}

export function checkPromotionValidationFun(configList) {
  const upAddContent = []
  let product_infos = []
  const cheakConfig = {
    validate_type: 1,
    participate_type: 1,
    activity_tool_type: 7,
    activity_tool_discount_type: 4,
    start_time: "",
    end_time: "",
    product_infos: [],
    support_type: 1
  }
  configList.forEach((item) => {
    // ${item.business_code}
    let keyItem = `${item.indexkey}${item.start_time}${item.end_time}`
    if (!upAddContent.find((items) => keyItem === items.onkey)) {
      // console.log('item', new Date(item.begin_time).getTime() / 1000, new Date(item.end_time).getTime() / 1000)
      upAddContent.push({
        onkey: keyItem,
        config: item,
        ckproduct: []
      })
    }
  })
  return new Promise((resolve, reject) => {
    const copynoContentList = JSON.parse(JSON.stringify(noContentList))
    upAddContent.forEach((copyPredect, ind) => {
      copyPredect.ckproduct = JSON.parse(JSON.stringify(noContentList))
    })
    while (copynoContentList.length > 0) {
      let infoList = []
      const splits = copynoContentList.splice(0, 100)

      splits.map((listconetr) => {
        // datas.push(...listconetr)
        infoList.push({
          channel_id: "0",
          channel_type: 0,
          product_id: listconetr.product_id
        })
      })
      product_infos.push(infoList)
    }
    // 检查活动的情况
    const upInfoContentData = upAddContent.map((getItem) => {
      const copyInitData = JSON.parse(JSON.stringify(cheakConfig))
      copyInitData.start_time = new Date(getItem.config.start_time).getTime()
      copyInitData.end_time = new Date(getItem.config.end_time).getTime()
      const getOyer = product_infos.map((gters) => {
        copyInitData.product_infos = gters
        return checkPromotionProductList(copyInitData)
      })
      return new Promise((resv, rejc) => {
        Promise.all(getOyer).then((res) => {
          resv(res)
        })
      })

      // copyInitData.product_infos = []
    })
    // console.log('检查的配置', upInfoContentData)

    // console.log('检查的商品', product_infos)
    // 过滤相同的活动配置，即活动类型与活动时间完全相同的活动表示为同一活动（只需获取一份商品列表）
    Promise.all(upInfoContentData).then((res) => {
      // console.log('检查的结果', res)
      // console.log('可以对应到shopid上了', res)
      res.forEach((prdlitAls, index) => {
        prdlitAls.forEach((prdlit) => {
          if (!prdlit.code) {
            console.log("prdlit.dataprdlit.data", prdlit.data)
            prdlit.data &&
              prdlit.data.product_check_infos &&
              Object.keys(prdlit.data.product_check_infos).forEach(
                (key, int) => {
                  const getPrdInfo = prdlit.data.product_check_infos[key]
                  // console.log('getPrdInfo', getPrdInfo)
                  const getTilenIds = upAddContent[index].ckproduct.find(
                    (refoterItem, indesr) => {
                      // refoterItem.
                      // return refoterItem.product_id === getPrdInfo.product_id
                      // console.log('refoterItem', refoterItem)

                      return key.includes(refoterItem.product_id)
                    }
                  )
                  // console.log('getTilenIds', key, getTilenIds)
                  if (getTilenIds) {
                    getTilenIds.chrackData = getPrdInfo
                    // if (getTilenIds.stock_num == 0) {
                    //     getTilenIds.chrackData = {
                    //         check_pass: false,
                    //         reject_reason: '商品库存为0, 不可用'
                    //     }
                    // } else {
                    //     getTilenIds.chrackData = getPrdInfo

                    // }
                  }
                }
              )
            // prdlit.data.product_check_infos.forEach((contentItem, int) => {
            //     console.log('contentItem', contentItem, noContentList)
            // })
          }
        })
      })
      // console.log('所有活动所有商品检查完毕', upAddContent)
      resolve(upAddContent)
    })
  })
}
export async function checkPromotionNewPipeal(data, addCouponConfig, list) {
  let getTimetype
  console.log("data, addCouponConfig, list", data, addCouponConfig, list)
  const { start_apply_time, end_apply_time } = addCouponConfig
  if (data.discountType == 1) {
    getTimetype = {
      activity_tool_discount_type: 1,
      credit: Number((data.credit * 100).toFixed(0)),
      validate_type: 2,
      participate_type: 1,
      activity_tool_type: 7,
      support_type: 1,
      start_time: start_apply_time,
      end_time: end_apply_time,
      product_infos: []
    }
  }
  if (data.discountType == 2) {
    getTimetype = {
      activity_tool_discount_type: 3,
      threshold: Number((data.threshold * 100).toFixed(0)),
      credit: Number((data.credit * 100).toFixed(0)),
      validate_type: 2,
      participate_type: 1,
      activity_tool_type: 7,
      support_type: 1,
      start_time: start_apply_time,
      end_time: end_apply_time,
      product_infos: []
    }
  }
  if (data.discountType == 3) {
    getTimetype = {
      activity_tool_discount_type: 4,
      discount: Number((data.discount * 10).toFixed(0)),
      validate_type: 2,
      participate_type: 1,
      activity_tool_type: 7,
      support_type: 1,
      start_time: start_apply_time,
      end_time: end_apply_time,
      product_infos: []
    }
  }
  getTimetype.product_infos = list.map((res) => {
    return {
      product_id: res.product_id,
      channel_type: 0,
      channel_id: "0"
    }
  })
  const getAtserNow = await checkPromotionProductList(getTimetype)
  if (!getAtserNow.code) {
    if (getAtserNow.data.product_check_infos) {
      Object.keys(getAtserNow.data.product_check_infos).forEach((key) => {
        if (!getAtserNow.data.product_check_infos[key]?.check_pass) {
          const getGter = list.find((itemtres) => {
            return key.includes(itemtres.product_id)
          })
          getGter.chrackData = getAtserNow.data.product_check_infos[key]
        }
      })
    }
  }
  console.log("刷新列表结果", getAtserNow)
  return list
}
